package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("user")
public class LoginController {

    public static String ACCESS_TOKEN="access_token";
    @Reference(timeout = 3000,check = false)
    IKaptchaService iKaptchaService;
    @Reference(timeout = 3000,check = false)
    ILoginService iLoginService;

    @PostMapping("login")
    @Anoymous
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse response){

        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");

        // 校验验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(uuid);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // 校验失败，响应错误信息
        if(!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        UserLoginRequest loginRequest = new UserLoginRequest();
        loginRequest.setUserName(userName);
        loginRequest.setPassword(userPwd);
        UserLoginResponse loginResponse = iLoginService.login(loginRequest);
        if(!loginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(loginResponse.getMsg());
        }
        Cookie cookie = new Cookie(ACCESS_TOKEN, loginResponse.getToken());
        cookie.setMaxAge(3600);
        cookie.setPath("/");
        response.addCookie(cookie);

        return new ResponseUtil<>().setData(loginResponse);
    }


    @GetMapping("login")
    public ResponseData checkLogin(HttpServletRequest request){

        String userInfo = (String) request.getAttribute("userInfo");

        if (userInfo==null){
            return new ResponseUtil<>().setErrorMsg("token已失效");
        }

        CheckLoginRequest checkLoginRequest = new CheckLoginRequest();
        checkLoginRequest.setUserInfo(userInfo);
        CheckLoginResponse response = iLoginService.checkLogin(checkLoginRequest);

        return new ResponseUtil<>().setData(response);
    }
}
